﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Common.Locator;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Web.ApplicationRuntime;
using Fuse8.ContentManagementFramework.Domain.Bases;

namespace Fuse8.ContentManagementFramework.Administration.Controls
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class CmsAuthorizeAttribute : AuthorizeAttribute
    {
        private bool _shouldRedirectToNoRightsPage = false;

        public string UserGroups { get; set; }

        public string RedirectNoRightUrl { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            Guard.ArgumentNotNull(httpContext, "httpContext");

            bool result = false;

            var user = DependencyServiceLocator.Current.GetInstance<ICmsContext>().ContextUser;

            if ((user != null) && !(user is CmsAnonimousUser))
            {
                var membershipService = DependencyServiceLocator.Current.GetInstance<IMembershipService>();

                result = membershipService.IsUserInGroup(user.LoginName, PredefinedUserGroups.AdministrationAccess);

                if (result && !string.IsNullOrWhiteSpace(UserGroups))
                {
                    var parsedUserGroups = UserGroups.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    result = parsedUserGroups.Any(p => membershipService.IsUserInGroup(user.LoginName, p));

                    _shouldRedirectToNoRightsPage = !result;
                }
            }
            else
            {
                result = false;
            }

            return result;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!_shouldRedirectToNoRightsPage)
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                filterContext.Result = new HttpCmsUserHasNoRightsResult(RedirectNoRightUrl ?? "/admin/cmsaccount/userhasnorights");
            }
        }
    }
}